//
//  HomePageViewController.m
//  Business
//
//  Created by macox on 16/9/26.
//  Copyright © 2016年 macox. All rights reserved.
//

#import "HomePageViewController.h"
#import "OrderManagerViewController.h"
#import "HomeModel.h"
#import "RootViewController.h"
#import "RuZhuViewController.h"
#import "ProductCentersViewController.h"
#import "ShopSetViewController.h"
#import "ScanQRCodeViewController.h"
#import "SGGenerateQRCodeVC.h"
#import "SGScanningQRCodeVC.h"
#import <AVFoundation/AVFoundation.h>
#import "SGAlertView.h"
#import "ReleaseCommodityViewController.h"
#import "CommodityWarehouseViewController.h"
@interface HomePageViewController ()

@property (weak, nonatomic) IBOutlet UILabel *OnLineAccount;
@property (weak, nonatomic) IBOutlet UILabel *RefundedLabel;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *orderNumLabel;//订单数
@property (weak, nonatomic) IBOutlet UILabel *waiteNumberLabel;//待发货订单数
@property (weak, nonatomic) IBOutlet UILabel *tuikuanNumLabel;//待退款订单数
@property (weak, nonatomic) IBOutlet UILabel *moneyNumLabel;//成交金额
@property (nonatomic , strong) NSMutableArray *ChanelDataArray;
@property (strong, nonatomic) IBOutlet UILabel *storeName;
@property (strong, nonatomic) IBOutlet UILabel *PhoneNum;
@property (weak, nonatomic) IBOutlet UIButton *LogoImageBtn;
@property (weak, nonatomic) IBOutlet UILabel *AllMoneyLabel;
@property (weak, nonatomic) IBOutlet UILabel *AllOrderNum;
@property (weak, nonatomic) IBOutlet UIView *OneView;
@property (weak, nonatomic) IBOutlet UIView *TwoView;
@property (weak, nonatomic) IBOutlet UIView *ThreeView;


@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.ThreeView.layer setMasksToBounds:YES];
    self.ThreeView.layer.cornerRadius = 15;
    
    _OneView.layer.masksToBounds = YES;
    self.navigationController.tabBarController.tabBar.tintColor = [UIColor colorWithHue:0.23 saturation:0.65 brightness:0.71 alpha:1.00];
    
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:_OneView.bounds byRoundingCorners: UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii: (CGSize){5.0f, 5.0f}].CGPath;
    
    _OneView.layer.mask = maskLayer;
    
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
//    self.tabBarController.tabBar.hidden = NO;
    [self  requestDataInfo];
    [self Today];
    [self TotalBtn];
    NSDictionary *param = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN};
    [GDJHttpTool get:HomePageToday params:param success:^(id responseObj) {
        //        NSLog(@"%@", responseObj);
        //        NSLog(@"%@", param);
        if ([[responseObj objectForKey:@"Err"] intValue]) {
            
        }else{
            
            NSDictionary *dataArr = [responseObj objectForKey:@"HomeToDay"];
            HomeModel *model = [HomeModel mj_objectWithKeyValues:dataArr];
            _orderNumLabel.text = [NSString stringWithFormat:@"%@",model.OrderCount] ;
            _waiteNumberLabel.text = [NSString stringWithFormat:@"%@",model.WaitDeliveryCount] ;
            _tuikuanNumLabel.text = [NSString stringWithFormat:@"%@",model.WaitBackCount] ;
            _moneyNumLabel.text = [NSString stringWithFormat:@"%.2f元",model.Total];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
- (void)requestDataInfo{
    NSDictionary *param = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN};
    [GDJHttpTool get:Info params:param success:^(id responseObj) {
        NSLog(@"======------%@", responseObj);
        NSLog(@"====%@", param);
        if ([[responseObj objectForKey:@"Err"] intValue]) {
            
        }else{
            
            NSDictionary *dataArr = [responseObj objectForKey:@"ShopSetting"];
            
            HomeModel *model = [HomeModel mj_objectWithKeyValues:dataArr];
            NSLog(@"%@",model.ShopName);
            
            [[NSUserDefaults standardUserDefaults]setObject: model.ShopName forKey:@"ShopName"];
            _storeName.text = model.ShopName;
            _PhoneNum.text = GETPHONE;
            
            
            NSString *imageStr = [NSString stringWithFormat:@"%@%@",ReleaseORDebug,model.Logo];
            NSLog(@"====-----%@",imageStr);
            [[NSUserDefaults standardUserDefaults]setObject: imageStr forKey:@"ShopLogo"];
            //            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageStr]];
            //店铺logo
            if (model.Logo == nil) {
                [_LogoImageBtn setImage:[UIImage imageNamed:@"gandaji"] forState:UIControlStateNormal];
            }else{
                [_LogoImageBtn.layer setMasksToBounds:YES];
                [_LogoImageBtn.layer setCornerRadius:30.0];//设置矩形四个圆角半径
                NSString *imageStr = [NSString stringWithFormat:@"%@",SHOPLOGO];
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageStr]];
                [_LogoImageBtn setImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
            }
            
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)Today {
    NSLog(@"今日");
    NSDictionary *param = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN};
    [GDJHttpTool get:HomePageToday params:param success:^(id responseObj) {
                NSLog(@"%@", responseObj);
        //        NSLog(@"%@", param);
        if ([[responseObj objectForKey:@"Err"] intValue]) {
            
        }else{
            
            NSDictionary *dataArr = [responseObj objectForKey:@"HomeToDay"];
            
            HomeModel *model = [HomeModel mj_objectWithKeyValues:dataArr];
            _orderNumLabel.text = [NSString stringWithFormat:@"%@",model.OrderCount] ;
            _waiteNumberLabel.text = [NSString stringWithFormat:@"%@",model.WaitDeliveryCount] ;
            _tuikuanNumLabel.text = [NSString stringWithFormat:@"%@",model.WaitBackCount] ;
            _moneyNumLabel.text = [NSString stringWithFormat:@"%.2f元",model.Total];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
- (void)TotalBtn{
    NSLog(@"累计");

    NSDictionary *param = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN};
    [GDJHttpTool get:HomePageTotal params:param success:^(id responseObj) {
                NSLog(@"----%@", responseObj);
                NSLog(@"==-----%@", param);
        if ([[responseObj objectForKey:@"Err"] intValue]) {
            
        }else{
            
            NSDictionary *dataArr = [responseObj objectForKey:@"HomeDays"];
            
            HomeModel *model = [HomeModel mj_objectWithKeyValues:dataArr];
            _AllOrderNum.text = [NSString stringWithFormat:@"%@",model.OrderCount] ;
            _OnLineAccount.text = [NSString stringWithFormat:@"%@",model.OnlineTotle] ;
            _RefundedLabel.text = [NSString stringWithFormat:@"%@",model.SaoMaoTotle] ;
            _AllMoneyLabel.text = [NSString stringWithFormat:@"%.2f元",model.Total];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
- (IBAction)ReleaseProductBtn:(UIButton *)sender {
    NSLog(@"发布商品");
    [NNSingleton sharedSingleton].releasePosition = @"自定义添加";
    [NNSingleton sharedSingleton].pop_String = @"自定义";
    ReleaseCommodityViewController *fabuVc = [[ReleaseCommodityViewController alloc]init];
    [self.navigationController pushViewController:fabuVc animated:YES];
}
- (IBAction)OrderManagerBtn:(UIButton *)sender {
    NSLog(@"商品中心");
    ProductCentersViewController * productCenterVC = [[ProductCentersViewController  alloc]init];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    [self.navigationController pushViewController:productCenterVC animated:YES];

}

#pragma mark -- 店铺设置
- (IBAction)CouponManagerBtn:(UIButton *)sender {
    NSLog(@"店铺设置");
    [self storeSettingsDataRequestLoad];
}
#pragma mark -- 扫码添加商品
- (IBAction)scanCodeReleaseGoodsButton:(id)sender {
    // 1、 获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if(authStatus == AVAuthorizationStatusAuthorized){
            NSLog(@"允许状态");
            SGScanningQRCodeVC *VC = [[SGScanningQRCodeVC alloc] init];
            [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
            [self.navigationController.navigationBar setShadowImage:nil];
            [self.navigationController pushViewController:VC animated:YES];
        }else if (authStatus == AVAuthorizationStatusDenied)
        {
            NSLog(@"不允许状态，可以弹出一个alertview提示用户在隐私设置中开启权限");
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"未获得授权使用摄像头" message:@"请在iOS“设置”-“隐私”-“相机”中打开" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:nil];
               
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
        else if (authStatus == AVAuthorizationStatusNotDetermined)
        {
            NSLog(@"系统还未知是否访问，第一次开启相机时");
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                //*******************先回主线程
                if (granted) {
                    //第一次用户接受
                }else{
                    //用户拒绝
                }
            }];

        }
    } else {
        SGAlertView *alertView = [SGAlertView alertViewWithTitle:@"⚠️ 警告" delegate:nil contentTitle:@"未检测到您的摄像头, 请在真机上测试" alertViewBottomViewType:(SGAlertViewBottomViewTypeOne)];
        [alertView show];
    }

}
#pragma mark -- 从商品库push
- (IBAction)commodityWarehouseAdd:(id)sender {
    CommodityWarehouseViewController *commodityW = [[CommodityWarehouseViewController alloc]init];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    [self.navigationController pushViewController:commodityW animated:YES];
}

- (IBAction)OrderManagerBBB:(id)sender {
    NSLog(@"订单管理");
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    RootViewController *rootVC = [story instantiateViewControllerWithIdentifier:@"mainVC"];
    self.view.window.rootViewController = rootVC;
    rootVC.selectedIndex = 1;
}

#pragma mark -- 数据请求加载
- (void)storeSettingsDataRequestLoad{
    [GDJHttpTool get:StoreSettingsLoad params:@{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN} success:^(id responseObj) {
        NSLog(@"电台情歌 %@",responseObj);
        [SVProgressHUD showWithStatus:@"正在加载"];
        //查看错误码
        NSInteger err = [[responseObj valueForKey:@"Err"]integerValue];
        NSLog(@"争取吧%ld",(long) err);
        if (err == 0) {
            [SVProgressHUD dismiss];
            [NNSingleton sharedSingleton].shopsData = responseObj[@"ShopSetting"];
            NSLog(@"哈哈哈哈  %@",[NNSingleton sharedSingleton].shopsData);
            ShopSetViewController *shopSetVC = [[ShopSetViewController alloc]initWithNibName:@"ShopSetViewController" bundle:nil];
      
            [self.navigationController pushViewController:shopSetVC animated:YES];
        }else if (err == 110) {
            [SVProgressHUD showErrorWithStatus:@"您尚未提交商家入驻申请"];
            return ;
        }
        else if (err == 999) {
            [SVProgressHUD showErrorWithStatus:responseObj[@"ErrMsg"]];
            return ;
        }
    }failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
